﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;


/// <summary>
/// Summary description for ShoppingCart
/// </summary>
public class ShoppingCart
{
    public List<CartItem> Items { get; private set; }

    public static readonly ShoppingCart Instance;

    static ShoppingCart()
    {
        //
        // TODO: Add constructor logic here
        //

        if (HttpContext.Current.Session["ShoppingCart"] == null)
        {
            Instance = new ShoppingCart();
            Instance.Items = new List<CartItem>();
            HttpContext.Current.Session["ShoppingCart"] = Instance;
        }
        else
        {
            Instance = (ShoppingCart)HttpContext.Current.Session["ShoppingCart"];
        }
    }
    protected ShoppingCart() { }

    #region Modification Items

    //add Item
    public void AddItem(int _productID)
    {
        //tao CartItem moi
        CartItem newItem = new CartItem(_productID);
        //kiem tra neu da co san pham trong gio hang roi
        //thi tong san pham tang nen
        if (Items.Contains(newItem))
        {
            foreach (CartItem item in Items)
            {
                if (item.Equals(newItem))
                {
                    item.Quantity++;
                    return;
                }
            }
        }
        else
        {
            //them san pham moi neu chua co
            newItem.Quantity = 1;
            Items.Add(newItem);
        }

    }

    public void RemoveItem(int _productID)
    {
        CartItem removeItem = new CartItem(_productID);
        Items.Remove(removeItem);
    }

    public void SetItemQuantity(int _productId, int _quantity)
    {
        if (_quantity == 0)
        {
            RemoveItem(_productId);
            return;
        }
        //tim sam pham va cap nhap
        CartItem updateItem = new CartItem(_productId);
        foreach (CartItem item in Items)
        {
            if (item.Equals(updateItem))
            {
                item.Quantity = _quantity;
                return;
            }
        }
    }

    public decimal GetSubTotal()
    {
        decimal subTotal = 0;
        foreach (CartItem item in Items)
        {
            subTotal += item.TotalPrice;
        }
        return subTotal;
    }

    #endregion
}
